package cn.paul.wechatshop.service.impl;

import cn.paul.wechatshop.common.Const;
import cn.paul.wechatshop.common.ServerResponse;
import cn.paul.wechatshop.dao.OrderDetailDao;
import cn.paul.wechatshop.dto.OrderDTO;
import cn.paul.wechatshop.entity.OrderDetail;
import cn.paul.wechatshop.exception.WechatshopException;
import cn.paul.wechatshop.service.IBuyerService;
import cn.paul.wechatshop.service.IOrderMasterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;


/**
 * @author 徐凌峰
 * @date 2017/12/29
 */
@Service
@Slf4j
public class BuyerServiceImpl implements IBuyerService {
    @Autowired
    private IOrderMasterService iOrderMasterService;
    @Autowired
    private OrderDetailDao orderDetailDao;

    @Override
    public OrderDTO find(String openid, String orderId) {
        OrderDTO orderDTO = checkOrderOwner(openid, orderId);
        if (orderDTO == null) {
            log.error("[取消订单]订单不存在,orderId={}", orderId);
            throw new WechatshopException(Const.ResultEnum.ORDER_NOT_EXISTS);
        }
        List<OrderDetail> orderDetailList = orderDetailDao.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new WechatshopException(Const.ResultEnum.ORDER_DETAIL_NOT_EXISTS);
        }
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }

    @Override
    public ServerResponse cancel(String openid, String orderId) {
        if (checkOrderOwner(openid, orderId) == null) {
            log.error("[取消订单]订单不存在,orderId={}", orderId);
            throw new WechatshopException(Const.ResultEnum.ORDER_NOT_EXISTS);
        }
        return iOrderMasterService.cancel(orderId);

    }

    /**
     * 判断订单是否属于当前用户
     *
     * @param openid
     * @param orderId
     * @return
     */
    private OrderDTO checkOrderOwner(String openid, String orderId) {
        OrderDTO orderDTO = iOrderMasterService.findOne(orderId).getData();
        if (orderDTO == null) {
            return null;
        }
        if (!orderDTO.getBuyerOpenid().equalsIgnoreCase(openid)) {
            throw new WechatshopException(Const.ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;

    }
}
